<template>
  <div>
    <el-card>
      <div class="search">
        <el-form :model="querys" :inline="true">
          <el-form-item label="状态" prop="status">
            <el-select v-model="querys.authStatus" placeholder="全部" clearable style="width: 200px">
              <el-option label="待审核" :value="0" />
              <el-option label="通过" :value="1" />
              <el-option label="审核不通过" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleData"><i-ep-search />搜索</el-button>
            <el-button @click="resetQuery">
              <i-ep-refresh />
              重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-button type="danger" :disabled="ids.length === 0" @click="deleteList()"
        v-hasPerm="['sys:user:delete']"><i-ep-delete />删除</el-button>
    </el-card>
    <div v-loading="loading" class="flex justify-center flex-col items-center">
      <el-table :data="tableData" @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column fixed type="index" :index="indexMethod" label="序号" width="80" />
        <el-table-column prop="username" label="用户名" width="100" />
        <el-table-column prop="authKey" label="认证一卡通" width="120" />
        <el-table-column label="图片" width="180">
          <template #default="scope">
            <!-- <img :src="scope.row.authImg" alt="" style="width: 100%; height: 100px" /> -->
						<el-image
      							style="width: 100%; height: 100px"
     							 :src="scope.row.authImg"
     							 :zoom-rate="1.2"
      							:max-scale="7"
     							 :min-scale="0.2"
     							 :preview-src-list="[scope.row.authImg]"
										:preview-teleported="true"
										hide-on-click-modal
   							 />
          </template>
        </el-table-column>

        <el-table-column prop="realName" label="真实姓名" width="100" />
        <el-table-column prop="role" label="身份" width="85" />
        <el-table-column prop="authStatus" label="审核状态" width="105">
          <template #default="scope">
            <el-tag v-if="scope.row.authStatus === 'waiting'" type="info">待审核中</el-tag>
            <el-tag v-else-if="scope.row.authStatus === 'pass'" type="success">审核通过</el-tag>
            <el-tag v-else-if="scope.row.authStatus === 'failed'" type="danger">审核不通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="managerUsername" label="审核人" width="100" />
        <el-table-column prop="manageTime" label="审核时间" width="160" />

        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" @click="handleClick(scope.row)">审批</el-button>
            <el-button type="danger" @click="deleteAuthentication(scope.row.id)"
              v-hasPerm="['sys:user:delete']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-model:current-page="querys.pageNum" v-model:page-size="querys.pageSize"
        :page-sizes="[10, 20, 30, 50]" background layout="total, sizes, prev, pager, next, jumper" :total="dataTotal"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" class="py-12px" />
    </div>
    <el-dialog v-model="dialogVisible" title="认证审核" width="30%" align-center>
      <el-form :model="authmanageForm">
        <el-form-item label="审核状态">
          <el-radio-group v-model="authmanageForm.status">
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="2">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="authmanageForm.roleList" multiple placeholder="请选择">
            <el-option v-for="item in selectRoleList" :key="item[1]" :label="item[0]" :value="item[1]" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="manageAuthentication()">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  getUserPage,
  deleteUserPage,
  distributeRole,
  deleteById,
  manage
} from "@/api/authentication";
import { authRoleListType, authenticationList, authmanageFormType } from "@/api/authentication/type";

const loading = ref(false);

let tableData = ref<authenticationList[]>();
let dataTotal = ref<number>();
let selectRoleList = ref()
let roleList = ref<authRoleListType>()
let querys = reactive<authenticationList>({
  pageNum: 1,
  pageSize: 10,
});
//删除的ids
const ids = ref([]);
let dialogVisible = ref<boolean>(false)
let authmanageForm: authmanageFormType = reactive({
  id: 0,
  status: -1,
  roleList: []
})

const indexMethod = (index: number) => {
  return index + (querys.pageNum - 1) * querys.pageSize + 1;
};

function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

//删除
async function deleteAuthentication(id: number) {
  await ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteById(id).then(() => {
      ElMessage.success("删除成功");
      handleData();
    });
  });
}

async function deleteList() {
  let keyIds = ids.value as number[];
  await ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteUserPage(keyIds).then(() => {
      ElMessage.success("删除成功");
      handleData();
    });
  });
}

async function manageAuthentication() {
  await manage(authmanageForm)
    .then(() => {
      ElMessage.success("审批成功");
      authmanageForm = {
        id: 0,
        status: -1,
        roleList: []
      }
      handleData()
    })
    .catch((error) => {
      console.error("Error:", error);
    })
  dialogVisible.value = false
}
function handleClick(data: any) {
  authmanageForm.id = data.id
  switch (data.role) {
    case '教师': authmanageForm.roleList = [roleList.value?.教师 as string]; break
    case '系统管理员': authmanageForm.roleList = [roleList.value?.系统管理员 as string]; break
    default: authmanageForm.roleList = [roleList.value?.普通学生 as string];
  }
  switch (data.authStatus) {
    case 'waiting': authmanageForm.status = 0; break
    case 'pass': authmanageForm.status = 1; break
    case 'failed': authmanageForm.status = 2; break
    default: authmanageForm.status = -1;
  }
  dialogVisible.value = true
}

//重置

function resetQuery() {
  handleData();
}

//获取认证管理列表
async function handleData() {
  loading.value = true
  await getUserPage(querys)
    .then(({ data }) => {
      tableData.value = data.list;
      dataTotal.value = data.total
    })
    .catch((error) => {
      console.error("Error:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

//获取分配角色列表
async function getAuthRoleList() {
  await distributeRole()
    .then(({ data }) => {
      selectRoleList.value = Object.entries(data);
      roleList.value = data;
    })
    .catch((error) => {
      console.error("Error:", error);
    });
}

const handleSizeChange = (val: number) => {
  querys.pageSize = val
  handleData()
}
const handleCurrentChange = (val: number) => {
  querys.pageNum = val
  handleData()
}

onMounted(() => {
  handleData();
  getAuthRoleList();
});
</script>
